package com.tl.web05.controller;

import com.tl.web05.utils.Captcha;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet(name = "CaptchaServlet", urlPatterns = "/captcha")
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Captcha captcha = Captcha.getInstance();
        captcha.set(100, 40);
        String codeStr = captcha.generateCaptcha();
        HttpSession session = req.getSession();
        session.setAttribute("captcha", codeStr);
        // 生成一个图片返给前端
        BufferedImage bufferedImage = captcha.generateCheckImg(codeStr);
        // 获取响应输出流
        OutputStream os = resp.getOutputStream();
        // 通过ImageIO 的api 把图片输出到页面
        ImageIO.write(bufferedImage, "jpg", os);
    }
}
